package taos

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"sync"
)

var (
	instances Database
	once      sync.Once
)

// DB 返回一个数据库类型连接的单例
func DB() (db Database, err error) {
	once.Do(func() {
		instances, err = GetDB()
	})
	return instances, err
}

// GetDB 返回数据库实例
func GetDB() (db Database, err error) {
	link := g.Cfg().MustGet(context.Background(), "taos.tdengine.link", "root:taosdata@ws(127.0.0.1:6041)/")
	driverName := g.Cfg().MustGet(context.Background(), "taos.tdengine.type", "taosWS")
	dbName := g.Cfg().MustGet(context.Background(), "taos.tdengine.dbName", "")
	maxOpenConns := g.Cfg().MustGet(context.Background(), "taos.tdengine.maxOpenConns", 200)
	maxIdleConns := g.Cfg().MustGet(context.Background(), "taos.tdengine.maxIdleConns", 80)

	db = &TdEngine{
		Link:         link.String(),
		DriverName:   driverName.String(),
		DbName:       dbName.String(),
		Database:     dbName.String(),
		MaxIdleConns: maxIdleConns.Int(),
		MaxOpenConns: maxOpenConns.Int(),
	}
	return
}
